package com.wpp.websocket.api;

import java.util.Collections;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentSkipListSet;

/**
 * @author thisisit
 * @class: UserSessionPool
 * @desc: TODO
 * @date: 2021/6/18 7:10
 */
public class UserSessionPool {
    public static final UserSessionPool INSTANCE = new UserSessionPool();

    public static UserSessionPool getInstance() {
        return INSTANCE;
    }

    Set<UserSession> userSessions;
    Set<String> onlineUserIds;

    private UserSessionPool() {
        this.userSessions = new ConcurrentSkipListSet<>();
        this.onlineUserIds = new ConcurrentSkipListSet<>();
    }

    public synchronized int size() {
        return userSessions.size();
    }

    public synchronized boolean add(UserSession session) {
        //存在并替换
        boolean exists = false;
        if (userSessions.contains(session)) {
            userSessions.remove(session);
            exists = true;
        }
        userSessions.add(session);
        onlineUserIds.add(session.getUserId());
        return exists;
    }

    public synchronized void remove(UserSession session) {
        if (userSessions.contains(session)) {
            userSessions.remove(session);
        }
        onlineUserIds.remove(session.getUserId());
    }

    public Set<UserSession> getUserSessions() {
        return Collections.unmodifiableSet(userSessions);
    }

    public Set<String> getOnlineUserIds() {
        return Collections.unmodifiableSet(onlineUserIds);
    }

}
